import { Component, OnInit, HostListener, ViewChild, ElementRef } from '@angular/core';
import { NotificationService, BullySubjectService } from 'app/shared/service';
import { NzModalService, NzInputDirective } from 'ng-zorro-antd';
import { Subject } from 'rxjs';
import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';
import { DisseminationService } from '../dissemination-management.service';
import { PublicService } from 'app/public/public.service';
import { TranslateService } from '@ngx-translate/core';

@Component({
    selector: 'itmp-message-category',
    templateUrl: './message-category.component.html',
    styleUrls: ['./message-category.component.css']
})
export class MessageCategoryComponent implements OnInit {
    createButton = false;
    editButton = false;
    deleteButton = false;
    printButton = false;
    search$ = new Subject<object>();
    pagination: any; // 分页数据的对象
    listOfData = null; // 列表数据的数组
    renderHeader = null; // 表头数据的数组
    toolbarList = [
        // 工具条栏
        // { className: 'icon-chakan' },
        // { className: 'icon-dingwei' },
        { className: 'icon-dayinfuyin-' }
        // { className: 'icon-screenfull' },
        // { className: 'icon-xiazai' }
    ];
    selectCategory = null;
    editId = null;
    isAdd = false;
    title: string;
    hasConfirm = false;
    searchData: any;
    accessButton = {
        Create: false,
        Edit: false,
        Delete: false,
        PRINT: false
    };
    @ViewChild(NzInputDirective, { read: ElementRef })
    inputElement: ElementRef;
    @HostListener('window:click', ['$event'])
    handleClick(e: MouseEvent): void {
        if (
            this.editId &&
            !this.hasConfirm &&
            // this.inputElement &&
            // this.inputElement.nativeElement !== e.target &&
            !e.target['classList'].contains('operate') &&
            !e.target['classList'].contains('editInput')
        ) {
            this.hasConfirm = true;
            // this.onSave({ keyCode: 13 });
            const tempTranslate = [
                { title: 'DisseminationManagement.Message_Category.Confirm' },
                { title: 'DisseminationManagement.Message_Category.Do you want to save this Category' },
                { title: 'DisseminationManagement.Message_Category.OK' },
                { title: 'DisseminationManagement.Message_Category.NO' }
            ];
            tempTranslate.forEach(item => {
                this.translate.get(item.title).subscribe((res: string) => {
                    item.title = res || '';
                });
            });
            this.modalService.confirm({
                nzTitle: '<i class="iconfont icon-pen01" style="font-size:24px"></i>' + tempTranslate[0].title,
                nzContent: '<p style="font-size:24px">' + tempTranslate[1].title + '?</p>',
                nzOkText: tempTranslate[2].title,
                nzOnOk: () => {
                    this.onSave({ keyCode: 13 });
                },
                nzCancelText: tempTranslate[3].title,
                nzOnCancel: () => {
                    if (this.isAdd) {
                        this.isAdd = false;
                        this.listOfData.splice(0, 1);
                        this.listOfData = [...this.listOfData];
                    } else {
                        this.getData();
                    }
                    this.editId = null;
                    this.hasConfirm = false;
                }
            });
        }
    }
    onSave(event) {
        if (event.keyCode === 27) {
            this.getData();
            this.editId = null;
            return;
        }
        if (event.keyCode !== 13) {
            return;
        }
        const inputEle = document.getElementById('editInput');
        if (!inputEle) {
            return;
        }
        if (!inputEle['value'] || inputEle['value'] === '') {
            this.msg.notify({ type: 'warning', path: 'DisseminationManagement.MessageLibrary.validate_category' });
            return;
        }
        const params = {
            categoryId: this.editId,
            categoryName: inputEle['value']
        };
        let ask;
        if (this.title === 'add') {
            ask = 'createCategory';
        } else {
            ask = 'updateCategory';
        }
        this.diss[ask](params).subscribe(res => {
            if (res.messagecode === '900101') {
                this.msg.notify({ type: 'warning', path: 'DisseminationManagement.MessageLibrary.repeat_category' });
                // this.hasConfirm = false;
                // return;
            }
            this.editId = null;
            if (this.hasConfirm) {
                this.hasConfirm = false;
            }
            this.getData();
        });
    }
    constructor(
        private modalService: NzModalService,
        private msg: NotificationService,
        private diss: DisseminationService,
        private pub: PublicService,
        private translate: TranslateService
    ) {}
    ngOnInit() {
        this.searchPipeSet();
        this.renderHeader = [
            {
                name: 'ID',
                key: null,
                value: 'category_id',
                isChecked: true
            },
            {
                name: 'Category_Name',
                key: null,
                value: 'category_name',
                isChecked: true
            }
        ];
        this.initData();
        this.getData();
        this.getButtonAccess();
    }
    getButtonAccess() {
        this.accessButton = this.pub.getButtonAccess('9', this.accessButton);
    }
    // 获取数据
    getData() {
        this.selectCategory = null;
        for (const item in this.searchData) {
            if (this.searchData.hasOwnProperty(item)) {
                if (this.searchData[item] === '') {
                    this.searchData[item] = null;
                }
            }
        }
        const params = {
            condition: this.searchData,
            pageNum: this.pagination.currentPage,
            pageSize: this.pagination.pageSize
        };
        this.diss.getCategoryList(params).subscribe(res => {
            const content = res.data;
            if (!content) {
                this.listOfData = [];
                return;
            }
            this.listOfData = content.content;
            this.pagination.currentSize = content.numberOfElements;
            this.pagination.totalEle = content.totolElements;
        });
    }
    // 初始化分页和搜索
    initData() {
        this.pagination = {
            totalEle: 10,
            pageSize: 10,
            currentPage: 1,
            currentSize: 10
        };
        this.searchData = {
            category_id: null,
            category_name: null
        };
        this.listOfData = [];
    }
    // 搜索(防抖)
    onSearch(name): void {
        this.search$.next({ name: this.searchData[name] });
    }
    // 防抖函数注册
    searchPipeSet() {
        this.search$.pipe(debounceTime(1000), distinctUntilChanged()).subscribe((kw: any) => {
            this.pagination.currentPage = 1;
            this.getData();
        });
    }
    // 分页控件改变事件
    onPageChange(e) {
        this.pagination.currentPage = e;
        this.getData();
    }
    onSizeChange(e) {
        this.pagination.pageSize = e;
        const total = this.pagination.totalEle;
        const curPage = this.pagination.currentPage;
        this.pagination.currentPage = Math.ceil(total / e) < curPage ? Math.ceil(total / e) : curPage;
        this.getData();
    }
    // 点击tr取值
    clickTR(i): void {
        this.listOfData.forEach((data, index) => {
            data.active = false;
            if (i === index) {
                // 点击每个tr给与样式active
                data.active = true;
                this.selectCategory = data;
            }
        });
    }
    // 刷新
    refresh(): void {
        // this.cancelActive();
        this.initData();
        this.getData();
    }
    // 新增
    addRow(event): void {
        event.preventDefault();
        event.stopPropagation();
        // 判断是否在编辑状态
        if (this.editId) {
            this.msg.notify({ type: 'warning', path: 'DisseminationManagement.MessageLibrary.save_notify' });
            return;
        }
        // 获取下一个ID
        const nextID = new Date().getTime();
        this.listOfData.forEach(item => {
            item.active = false;
        });
        this.listOfData = [
            {
                categoryId: nextID,
                categoryName: '',
                active: true
            },
            ...this.listOfData
        ];
        this.isAdd = true;
        this.editId = nextID;
        this.title = 'add';
    }
    // 编辑
    startEdit(event): void {
        event.preventDefault();
        event.stopPropagation();
        // 判断是否在编辑状态
        if (this.editId) {
            this.msg.notify({ type: 'warning', path: 'DisseminationManagement.MessageLibrary.save_notify' });
            return;
        }
        if (this.selectCategory) {
            this.editId = this.selectCategory.categoryId;
            this.title = 'edit';
            // this.cancelActive();
        } else {
            this.msg.notify({ type: 'warning', path: 'DisseminationManagement.MessageLibrary.select_notify' });
        }
    }
    // 删除
    delete(event): void {
        event.preventDefault();
        event.stopPropagation();
        if (this.selectCategory) {
            const tempTranslate = [
                { title: 'DisseminationManagement.MessageLibrary.Delete_Message' },
                { title: 'DisseminationManagement.MessageLibrary.Delete_Content' },
                { title: 'DisseminationManagement.MessageLibrary.Delete_Save' },
                { title: 'DisseminationManagement.MessageLibrary.Delete_Cancel' }
            ];
            tempTranslate.forEach(item => {
                this.translate.get(item.title).subscribe((res: string) => {
                    item.title = res || '';
                });
            });
            this.modalService.confirm({
                nzTitle: '<i class="iconfont icon-delete" style="font-size:24px"></i>' + tempTranslate[0].title,
                nzContent: '<p style="font-size:24px">' + tempTranslate[1].title + '?</p>',
                nzOkText: tempTranslate[2].title,
                nzOnOk: () => {
                    this.diss.deleteCategory(this.selectCategory.categoryId).subscribe(res => {
                        if (res.messagecode === '900102') {
                            this.msg.notify({ type: 'warning', path: 'DisseminationManagement.MessageLibrary.repeat_notify' });
                        } else {
                            if ((this.pagination.totalEle - 1) / this.pagination.pageSize === this.pagination.currentPage - 1) {
                                this.pagination.currentPage = 1;
                            }
                            this.getData();
                        }
                    });
                },
                nzCancelText: tempTranslate[3].title,
                nzOnCancel: () => {}
            });
        } else {
            this.msg.notify({ type: 'warning', path: 'DisseminationManagement.MessageLibrary.delete_notify' });
            // 提示用户没有选中项目
        }
    }
}
